/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package fileManager;

import com.jspsmart.upload.SmartUpload;
import dateManager.LookDateBean;
import friendManager.AddFriendServlet;
import friendManager.LookFriendBean;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.jsp.PageContext;
import javax.swing.JOptionPane;
import loginRegister.LoginBean;
import org.apache.jasper.compiler.TagConstants;

/**
 *
 * @author DELL
 */
public class FileUpServlet extends HttpServlet {

    private ServletConfig config;

    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        this.config = config;
    }

    final public ServletConfig getServletConfig() {
        return config;
    }

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        try (PrintWriter out = response.getWriter()) {
            /* TODO output your page here. You may use following sample code. */
            out.println("<!DOCTYPE html>");
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet FileUpServlet</title>");
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet FileUpServlet at " + request.getContextPath() + "</h1>");
            out.println("</body>");
            out.println("</html>");
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    public void wrong1() {
        String msg = "您还未上传文件，请继续上传！";
        String title = "信息提示";
        int type = JOptionPane.YES_NO_CANCEL_OPTION;
        JOptionPane.showMessageDialog(null, msg, title, type);

    }

    public void right() {
        String msg = "上传文件成功！";
        String title = "信息提示";
        int type = JOptionPane.YES_NO_CANCEL_OPTION;
        JOptionPane.showMessageDialog(null, msg, title, type);

    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=GBK");
       
        try {

            SmartUpload sup = new SmartUpload();
            sup.initialize(getServletConfig(), request, response);
            sup.upload();
            int count=0;
           
                   String title=null;
                           title=sup.getRequest().getParameter("title");
             log(title);
              
               String downtitle=sup.getRequest().getParameter("dtitle");
               log(downtitle);

            if(title.length()!=0){
            

            try {
                         
             count=sup.save("c:\\upload");
            } catch (Exception e) {
            }

                

            
           log(count + "个文件上传成功！！！！");
             Connection con = null;
            java.sql.Statement stmt = null;
            ResultSet rs = null;

            Class.forName("com.mysql.jdbc.Driver");

            String url = "jdbc:mysql://localhost:3306/person?useUnicode=true&characterEncoding=gbk";

            con = DriverManager.getConnection(url, "skyline", "739349");

            stmt = con.createStatement();
            String sql=null;
            String userName = null;
            HttpSession session = request.getSession();
            ArrayList login = (ArrayList) session.getAttribute("login");
            if (login == null || login.size() == 0) {
                response.sendRedirect("http://localhost:8081/PersonInforMSys/login.jsp");
            } else {
                for (int i = login.size() - 1; i >= 0; i--) {

                    LoginBean nn = (LoginBean) login.get(i);
                    userName = nn.getUserName();

                }
            }
            String name=null;
             String contentType=null;
            String size=null;
             
            
            for (int i = 0; i < sup.getFiles().getCount(); i++) {
                com.jspsmart.upload.File file = sup.getFiles().getFile(i);

                // 若文件不存在则继续 
                if (file.isMissing()) {
                    continue;
                }

                log(title);
                name=file.getFileName();
                log(name);
                
                contentType=file.getContentType();
                log(contentType);
                
                   size=Integer.toString(file.getSize());
                log(size);
                  log("1flhsssssssssssssssssssssssssssssssssssssssssss");
                sql="insert into  file(userName,title,name,contentType,size) values('" + userName + "','" + title + "','" + name + "','" + contentType + "','" + size + "')";
                stmt.executeUpdate(sql);
                log("2222222222222flhsssssssssssssssssssssssssssssssssssssssssss");
                   }
            ArrayList fileList = null;
                    fileList = new ArrayList();
                    String sql2 = "select * from file where userName='" + userName + "'";

                    rs = stmt.executeQuery(sql2);
                  
                    while (rs.next()) {
                         
                        LookFileBean ffBean = new LookFileBean();
                        ffBean.setTitle(rs.getString("title"));
                        ffBean.setName(rs.getString("name"));
                         ffBean.setContentType(rs.getString("contentType"));
                        ffBean.setSize(rs.getString("size"));
                        fileList.add(ffBean);
                        session.setAttribute("fileList", fileList);
                         
                    } 
              rs.close();
              stmt.close();
              con.close();
              right();
               response.sendRedirect("http://localhost:8081/PersonInforMSys/fileManager/fileUp.jsp");
            }
             else if(downtitle.length()!=0){
            
                
                            try {
                
                 Connection con = null;
            java.sql.Statement stmt = null;
            ResultSet rs = null;
            Class.forName("com.mysql.jdbc.Driver");
            HttpSession session = request.getSession();
            String url = "jdbc:mysql://localhost:3306/person";

            con = DriverManager.getConnection(url, "skyline", "739349");

            stmt = con.createStatement();
            
             String userName = null;
               
                ArrayList login = (ArrayList) session.getAttribute("login");
                if (login == null || login.size() == 0) {
                    response.sendRedirect("http://localhost:8081/PersonInforMSys/login.jsp");
                } else {
                    for (int i = login.size() - 1; i >= 0; i--) {

                        LoginBean nn = (LoginBean) login.get(i);
                        userName = nn.getUserName();

                    }
                }
            
            String sql = "select * from file where userName='" + userName + "' and title='" + downtitle + "'";
                
               rs = stmt.executeQuery(sql);
                String fileName=null;  
                    while (rs.next()) {
                         
                        fileName=rs.getString("name");
                         log(fileName);
                    }  
            
                     try {
            sup.downloadFile("c:\\upload\\"+fileName);
        } catch (Exception e) {
               log("error:",e);
        }
                
        } catch (Exception e) {
        }

 
          response.sendRedirect("http://localhost:8081/PersonInforMSys/fileManager/fileUp.jsp");   
            
            
            }
        } catch (Exception e) {
        }
        
    }
    
    
    

//
//                rs.close();;
//                stmt.close();
//                con.close();
//
//                right();
//                response.sendRedirect("http://localhost:8081/PersonInforMSys/friendManager/lookFriend.jsp");
//            }
//

//        }
//
//    }
//
//}

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
        protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
        public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
